package com.ccx.coachsite.webimage;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import com.ccx.coachsite.http.BitmapProgress;
import com.ccx.coachsite.http.ImageGetter;
import com.ccx.coachsite.http.ProgressListener;
import com.ccx.coachsite.util.CommonViewUtils;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.StringUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class HttpImage {

	/**
	 * 内存图片软引用缓冲
	 */
	private HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

	public final static String SDCARD_IMAGE_DIR = SdCardTool
			.getSdcardDir() + "/YYZL/cache";
	public final static String SDCARD_IMAGE_CACHE_DIR = SdCardTool
			.getSdcardDir() + "/YYZL/cache/";
	public final static long FIFTEEN_DAYS = 15 * 24 * 60 * 60 * 1000;

	private static final float ROUNDPX = 10.0F; // 圆角率

	public static String getFileNameMD5(String str) {
		return MD5.getMD5Str(str);
	}

	public static String getFilePath(String url) {
		return SDCARD_IMAGE_CACHE_DIR + getFileNameMD5(url);
	}

	// 加载图片，统一入口
	public static Bitmap loadBitmap(final String url,
			final ProgressListener<BitmapProgress> listener) {

		Bitmap bitmap = null;
		String cacheKey = getFileNameMD5(url);

		// 1、从缓存读取
		bitmap = BitmapCacheMgr.getInstance().getBitmap(cacheKey);
		if (bitmap != null)
			return bitmap;

		// 2、从sd卡读取
		bitmap = getBitmapFromSdCard(cacheKey);
		if (bitmap != null)
			return bitmap;

		// 3、从网络读取
		getBitmapFromUrl(url, cacheKey, listener);

		return bitmap;
	}

	/**
	 * 下载图片，并设置相应的view
	 * 
	 * @param url
	 *            绝对地址，需要拼装后传入
	 * @param view
	 */
	public static void loadBitmap(final String url, final View view) {
		loadBitmap(url, view, true, false);
	}

	/**
	 * 下载图片，并设置相应的View，同时可以设置当下载失败或者无图片时，是否隐藏掉裂图。
	 * 
	 * @param url
	 *            绝对地址，需要拼装后传入
	 * @param view
	 * @param isShow
	 *            是否显示图片，当图片不存在时，隐藏图片
	 * @param isRounded
	 *            是否显示圆角图片
	 */
	public static void loadBitmap(final String url, final View view,
			final boolean isShow, final boolean isRounded) {
		Context context = view.getContext();
		if (!CommonViewUtils.isNetConnectionAvailable(context)) {
			Log.e("网络异常，请检查网络连接！");
			// Toast.makeText(context, "网络异常，请检查网络连接！",
			// Toast.LENGTH_LONG).show();
			return;
		}

		Bitmap bitmap = loadBitmap(url, new ProgressListener<BitmapProgress>() {

			@Override
			public void onProgressUpdate(BitmapProgress entity) {
			}

			@Override
			public void onPostExecute(BitmapProgress entity) {
				setImageView(view, entity.getBitmap(), isShow, isRounded);
			}
		});

		if (bitmap != null)
			setImageView(view, bitmap, isShow, isRounded);
	}

	/**
	 * 设置圆角图片
	 * 
	 * @param url
	 * @param view
	 * @param isShow
	 *            是否显示图片，当图片不存在时，隐藏图片
	 */
	public static void loadRoundCornerBitmap(final String url, final View view,
			final boolean isShow) {
		loadBitmap(url, view, isShow, true);
	}

	/**
	 * 获取圆角Btimap
	 * 
	 * @param bitmap
	 * @param roundPx
	 *            圆角率
	 * @return
	 */
	private static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 设置图片到相应的View中。
	 * 
	 * @param view
	 * @param bitmap
	 */
	protected static void setImageView(Object view, Bitmap bitmap,
			boolean isShow, boolean isRounded) {
		if (isRounded) {
			bitmap = getRoundedCornerBitmap(bitmap, ROUNDPX);
		}

		if (view instanceof ImageView) {
			ImageView imageView = (ImageView) view;
			if (bitmap != null) {
				imageView.setImageBitmap(bitmap);
			} else {
				if (isShow) {
					// imageView.setImageResource(R.drawable.base_download_fail);
				} else {
					imageView.setVisibility(View.GONE);
				}

			}
			CommonViewUtils.showImageChange(imageView);
		} else if (view instanceof ViewGroup) {
			ViewGroup viewGroup = (ViewGroup) view;
			if (bitmap != null) {
				BitmapDrawable drawable = new BitmapDrawable(bitmap);
				viewGroup.setBackgroundDrawable(drawable);
			} else {
				if (isShow) {
					// viewGroup.setBackgroundResource(R.drawable.base_download_fail);
				} else {
					viewGroup.setVisibility(View.GONE);
				}
			}
		} else {
			Log.d("unknow view for bitmap!");
		}
	}

	// 从SD卡缓存找图片
	public static Bitmap getBitmapFromSdCard(String fileName) {

		return getBitmapFromSdCard(SDCARD_IMAGE_CACHE_DIR, fileName);
	}

	// 从SD卡缓存找图片
	public static Bitmap getBitmapFromSdCard(String fileDir, String fileName) {
		if (StringUtil.isEmpty(fileDir) || StringUtil.isEmpty(fileName))
			return null;

		if (!SdCardTool.exists())
			return null;

		String filePath = fileDir + fileName;
		if (!FileUtil.isFileExits(filePath))
			return null;
		return BitmapFactory.decodeFile(filePath);
	}

	public static void getBitmapFromUrl(final String url,
			final String cacheKey,
			final ProgressListener<BitmapProgress> listener) {

		if (StringUtil.isEmpty(url))
			return;

		Log.d("download bitmap, url: " + url);

		if (SdCardTool.exists()) { // sd卡挂载
			ImageGetter getter = new ImageGetter(SDCARD_IMAGE_CACHE_DIR,
					cacheKey);
			getter.setProgressListener(new ProgressListener<BitmapProgress>() {
				@Override
				public void onProgressUpdate(BitmapProgress progress) {
					listener.onProgressUpdate(progress);
				}

				@Override
				public void onPostExecute(BitmapProgress progress) {
					listener.onPostExecute(progress);
					if (progress.getBitmap() != null)
						BitmapCacheMgr.getInstance().saveBitmap(cacheKey,
								progress.getBitmap());
				}
			});
			getter.execute(url);

		} else { // sd卡未挂载
			Log.w("sdcard unmounted.");
			ImageGetter getter = new ImageGetter();
			getter.setProgressListener(new ProgressListener<BitmapProgress>() {
				@Override
				public void onProgressUpdate(BitmapProgress progress) {
					listener.onProgressUpdate(progress);
				}

				@Override
				public void onPostExecute(BitmapProgress progress) {
					listener.onPostExecute(progress);
					if (progress.getBitmap() != null)
						BitmapCacheMgr.getInstance().saveBitmap(cacheKey,
								progress.getBitmap());
				}
			});
			getter.execute(url);
		}
	}

	public static Bitmap decodeFile(String filePath, int quanlity) {
		Bitmap bitmap = null;
		try {
			if (quanlity == 1) {
				bitmap = BitmapFactory.decodeFile(filePath);
			} else {
				BitmapFactory.Options options = new Options();
				options.inSampleSize = quanlity;
				bitmap = BitmapFactory.decodeFile(filePath, options);
			}
		} catch (OutOfMemoryError e) {
			Log.e(e.getMessage(), e);
			// e.printStackTrace();
		} catch (Exception e) {
			Log.e(e.getMessage(), e);
			// e.printStackTrace();
		}

		return bitmap;
	}

	// clear overdue files
	public static void clearOverdue() {
		if (!SdCardTool.exists()) {
			Log.w("sdcard unmounted.");
			return;
		}
		File file = new File(SDCARD_IMAGE_CACHE_DIR);
		if (file.exists()) {
			File[] files = file.listFiles();

			File temp = null;
			for (int i = 0; i < files.length; i++) {
				temp = files[i];
				// 删除文件修改时间超过十五天的文件
				if (System.currentTimeMillis() - temp.lastModified() > FIFTEEN_DAYS) {
					temp.delete();
				}
			}
		}
	}

	// clear all cache file
	public static void clearCache() {
		if (!SdCardTool.exists()) {
			Log.w("sdcard unmounted.");
			return;
		}
		File file = new File(SDCARD_IMAGE_CACHE_DIR);
		if (file.exists()) {
			File[] files = file.listFiles();

			for (int i = 0; i < files.length; i++) {
				files[i].delete();
			}
		}
	}

}